package com.cskaoyan.service;

import com.cskaoyan.bean.AdExample;
import com.cskaoyan.bean.vo.AdminAdForListDataBean;
import com.cskaoyan.bean.vo.AdminAdForListItemBean;
import com.cskaoyan.mapper.AdMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class AdminAdServiceImp implements AdminAdService {

    @Autowired
    AdMapper adMapper;

    @Override
    public AdminAdForListDataBean<AdminAdForListItemBean> queryAdByNameAndContent(Integer page, Integer limit, String name, String content, String sort, String order) {
        PageHelper.startPage(page, limit);

        AdExample adExample = new AdExample();
        AdExample.Criteria criteria = adExample.createCriteria();

        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);
        if (content != null) {
            criteria.andContentLike("%" + content + "%");
        }
        adExample.setOrderByClause(sort + " " + order);
        List<AdminAdForListItemBean> adminAdForListItemBeans = adMapper.selectAdminAdForListItemBean(adExample);
        PageInfo<AdminAdForListItemBean> adminAdForListItemBeanPageInfo = new PageInfo<>(adminAdForListItemBeans);
        long total = adminAdForListItemBeanPageInfo.getTotal();
        AdminAdForListDataBean<AdminAdForListItemBean> dataBean = new AdminAdForListDataBean<>();
        dataBean.setItems(adminAdForListItemBeans);
        dataBean.setTotal(total);

        return dataBean;
    }

    @Override
    public Integer insertAd(AdminAdForListItemBean adBean) {
        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        adBean.setAddTime(dateTime);
        adBean.setUpdateTime(dateTime);
        Integer result = adMapper.insertAdByAdminAdForListItemBean(adBean);
        return result == 1 ? 200: 404;
    }

    @Override
    public Integer updateAdByAdminAdForListItemBean(AdminAdForListItemBean adBean) {
        adBean.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        Integer result = adMapper.updateByAdminAdForListItemBean(adBean);
        return result == 1 ? 200:404;
    }

    @Override
    public AdminAdForListItemBean getAdminAdForListItemBeanById(Integer id) {
        AdminAdForListItemBean result = adMapper.selectAdminAdForListItemBeanById(id);
        return result;
    }

    @Override
    public Integer deleteAdByAdminAdForListItemBean(AdminAdForListItemBean adBean) {
        adBean.setDeleted(true);
        adBean.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return adMapper.updateByAdminAdForListItemBean(adBean);
    }
}
